import axios from 'axios'
import {Toast,Notify} from 'vant'

const baseURL = 'http://h5project.cn:8300';
axios.defaults.baseURL = baseURL;

//拦截器
export function loaddingTip(){
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });
}
export function errorNotify(msg){ 
    Notify({ type: 'danger', message: msg, duration:1000 });
}

//请求发送之前
axios.interceptors.request.use(function(config){
    console.log(localStorage);
    config.headers['token']=localStorage.getItem('token')
    console.log(config);
    loaddingTip();
    return config

},function(error){
    errorNotify('网络异常')
    return Promise.reject(error);
})

//响应数据结束
axios.interceptors.response.use(function(response){

    Toast.clear();
    console.log(response.data)
    if(response.data.code==402 || response.data.code==500){
        // error 
        Notify({
            message: response.data.msg || '数据异常',
            color: '#ad0000',
            background: '#ffe1e1',
        });
    }
    if(response.data.code==3000 ){
        // error 
        Notify({
            message: response.data.msg ,
            color: '#ad0000',
            background: '#ffe1e1',
        });
        // 登录失效 
        // router.push({name:'login'})
    }


    return response

},function(error){
    errorNotify('服务器异常')
    return Promise.reject(error);
})


//get请求

export const get=function(url,params,headers){
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params,
            headers,
        }).then(res=>{
            resolve(res.data);
        }).catch(err=>{
            reject(err)
        })
    })
}

//post请求
export const post=function(url,body,params,headers){
    return new Promise(function(resolve,reject){ 
        axios.post(url,body,{
            params,
            headers,
        }).then(res=>{
            resolve(res.data);
        }).catch(err=>{
            reject(err)
        })
    })
}



export  {axios,baseURL}